import os
from functools import wraps

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, Session

from Logs.log_handle import get_log
from tools.yaml_handle import ReadYaml

# ──────────────── 日志配置 ────────────────
# 获取日志对象（日志文件名为当前脚本名）
log = get_log(os.path.split(__file__)[-1])

# ──────────────── 配置加载 ────────────────
root_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
config_path = os.path.join(root_path, "config.yaml")
config = ReadYaml(config_path).read_yaml
db_cfg = config.get("database", {})
host = db_cfg.get("host", "localhost")
user = db_cfg.get("user", "root")
password = db_cfg.get("password", "root")
database = db_cfg.get("database", "test_case")

# 拼接数据库连接 URL
DATABASE_URL = f"mysql+mysqlconnector://{user}:{password}@{host}/{database}"

# ──────────────── 创建数据库 Engine 和 Session ────────────────
engine = create_engine(
    DATABASE_URL,
    isolation_level="READ COMMITTED",
    pool_size=10,
    max_overflow=20,
    pool_pre_ping=True,
    echo=True
)

SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)


# ──────────────── 写操作事务管理装饰器 ────────────────
def transactional(func):
    """
    写操作事务管理装饰器
    """

    @wraps(func)
    def wrapper(*args, **kwargs):
        db: Session = SessionLocal()
        func_name = func.__name__
        log.info(f"[事务开始] 函数: {func_name}")
        try:
            result = func(*args, db=db, **kwargs)
            db.commit()
            log.info(f"[事务提交] 函数执行成功: {func_name}")
            return result
        except Exception as e:
            db.rollback()
            log.error(f"[事务回滚] 函数: {func_name} 异常: {e}")
            raise
        finally:
            db.close()
            log.info(f"[连接关闭] 函数: {func_name}")

    return wrapper


# ──────────────── 读操作（查询）装饰器 ────────────────
def db_session(func):
    """
    查询操作的装饰器（只读）
    """

    @wraps(func)
    def wrapper(*args, **kwargs):
        db: Session = SessionLocal()
        func_name = func.__name__
        log.info(f"[查询开始] 函数: {func_name}")
        try:
            return func(*args, db=db, **kwargs)
        except Exception as e:
            log.error(f"[查询失败] 函数: {func_name} 异常: {e}")
            raise
        finally:
            db.close()
            log.info(f"[连接关闭] 函数: {func_name}")

    return wrapper
